import my.common.File;
import my.socket.ServerSocket;
import my.socket.Socket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;

public class BioMain {

    static {
        System.load(BioMain.class.getResource("/").getPath() + "libepoll-http.so");
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);

        for (;;) {
            Socket socket = serverSocket.accept();
            ByteBuffer buf = ByteBuffer.allocateDirect(1024);
            while (true) {
                int read = File.read(socket.intValue(), buf, buf.position(), buf.limit());
                buf.position(read);
                buf.flip();
                String request = null;
                try {
                    request = StandardCharsets.UTF_8.newDecoder().decode(buf).toString();
                } catch (CharacterCodingException e) {
                    e.printStackTrace();
                }
                System.out.println(request);
                String response = "response\n";
                buf.clear();
                buf.put(response.getBytes());
                buf.flip();
                File.write(socket.intValue(), buf, buf.position(), buf.limit());
            }
        }
    }
}
